import {
  Component,
  OnInit,
  ChangeDetectorRef,
  ViewChild,
  TemplateRef,
} from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {
  NzMessageService,
  UploadFile,
  UploadXHRArgs,
  NzModalService,
} from 'ng-zorro-antd';
import { ShopService } from '../shop.service';
import {
  HttpRequest,
  HttpClient,
  HttpEvent,
  HttpEventType,
  HttpResponse,
} from '@angular/common/http';
import { STData, STChange, STComponent, STColumn } from '@delon/abc';

@Component({
  selector: 'detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css'],
})
export class DetailComponent implements OnInit {
  edit(tpl: TemplateRef<{}>, item: any): any {
    this.form2.reset();
    this.form2.patchValue({
      returnedDay: item.returnedDay,
      exchangeDay: item.exchangeDay,
      isDefault: item.isDefault,
      id: item.id,
    });

    this.modalSrv.create({
      nzTitle: '编辑退换货规则',
      nzContent: tpl,
      nzOnOk: () => {
        for (const i in this.form2.controls) {
          this.form2.controls[i].markAsDirty();
          this.form2.controls[i].updateValueAndValidity();
        }
        if (this.form2.invalid) return false;

        this.submitting = true;
        this._shopServer.createOrEditReturnedRule(this.form2.value).subscribe(
          res => {
            this.submitting = false;
            if (res.success) {
              this.msg.success(`操作成功`);
              this.getData();
            }
          },
          err => {
            this.submitting = false;
            this.msg.error(`操作失败`);
          },
        );
      },
    });
  }

  form: FormGroup;
  form2: FormGroup;
  form3: FormGroup;
  form4: FormGroup;
  submitting = false;

  fileList = [
    // {
    //   uid: -1,
    //   name: 'xxx.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // }
  ];
  previewImage = '';
  previewVisible = false;
  downloadPath = '';

  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 6,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 97, text: '异常', value: false, type: 'error', checked: false },
  ];

  @ViewChild('st')
  st: STComponent;
  @ViewChild('modalContent2')
  modalContent2: TemplateRef<{}>;

  columns: STColumn[] = [
    { title: 'ID', index: 'id' },
    { title: '最多几天换货', index: 'returnedDay' },
    { title: '最多几天退货', index: 'exchangeDay' },
    { title: '是否全店默认', index: 'isDefault' },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          click: (item: any) => this.edit(this.modalContent2, item),
        },
        {
          text: '删除',
          click: (item: any) => this.remove(item),
        },
      ],
    },
  ];

  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  add(tpl: TemplateRef<{}>) {
    this.form2.reset();
    this.modalSrv.create({
      nzTitle: '新建退换货规则',
      nzContent: tpl,
      nzOnOk: () => {
        for (const i in this.form2.controls) {
          this.form2.controls[i].markAsDirty();
          this.form2.controls[i].updateValueAndValidity();
        }
        if (this.form2.invalid) return false;

        this.submitting = true;
        this._shopServer.createOrEditReturnedRule(this.form2.value).subscribe(
          res => {
            this.submitting = false;
            if (res.success) {
              this.msg.success(`操作成功`);
              this.getData();
            }
          },
          err => {
            this.submitting = false;
            this.msg.error(`操作失败`);
          },
        );
      },
    });
  }

  stChange(e: STChange) {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        this.totalCallNo = this.selectedRows.reduce(
          (total, cv) => total + cv.callNo,
          0,
        );
        this.cdr.detectChanges();
        break;
      case 'filter':
        this.getData();
        break;
    }
  }

  remove(item: any) {
    this.modalSrv.confirm({
      nzTitle: '确认删除么?',
      nzContent: '点击确认，继续删除。点击取消，退出操作！',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        this._shopServer.deleteReturnedRule(item.id).subscribe(
          resp => {
            if (resp.success) {
              this.msg.success('操作成功');
              this.getData();
              
            } else this.msg.error(resp.bizMessage);
          },
          error => {
            this.msg.error('异常: ' + JSON.stringify(error));
          },
        );
      },
    });
  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);

    if (this.q.status !== null && this.q.status > -1)
      this.q.statusList.push(this.q.status);

    this.loading = false;

    this._shopServer.queryReturnedRuleList().subscribe(resp => {
      if (resp.success) {
        this.data = resp.data;
      }
    });
  }

  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private cdr: ChangeDetectorRef,
    private _shopServer: ShopService,
    private http: HttpClient,
    private modalSrv: NzModalService,
  ) {}

  // [nzCustomRequest]="customReq"
  customReq = (item: UploadXHRArgs) => {
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress: true,
      withCredentials: true,
    });

    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total) * 100;
          }
          // 处理上传进度条，必须指定 `percent` 属性来表示进度
          item.onProgress(event, item.file);
        } else if (event instanceof HttpResponse) {
          // 处理成功
          item.onSuccess(event.body, item.file, event);
          let obj = event.body as any;
          this.downloadPath = obj.downloadPath;
        }
      },
      err => {
        // 处理失败
        item.onError(err, item.file);
      },
    );
  };

  ngOnInit(): void {
    this.form = this.fb.group({
      shopName: [null, [Validators.required]],
      brandIntroduction: [null, [Validators.required]],
      telephone: [null, [Validators.required]],
      shopAddress: [null, [Validators.required]],
    });

    this.form2 = this.fb.group({
      id: [null],
      returnedDay: [null, [Validators.required]],
      exchangeDay: [null, [Validators.required]],
      isDefault: [null],
    });

    this.form3 = this.fb.group({
      fee: [null, [Validators.required]],
      fullFee: [null, [Validators.required]],
      info: [null],
    });

    this.form4 = this.fb.group({
      fee: [null, [Validators.required]],
      fullFee: [null, [Validators.required]],
      info: [null],
    });

    this._shopServer.queryById().subscribe(
      res => {
        console.log('success', res);
        if (res.success) {
          this.form.patchValue({
            shopName: res.data.shopName,
            brandIntroduction: res.data.brandIntroduction,
            telephone: res.data.telephone,
            shopAddress: res.data.shopAddress,
          });

          this.fileList = [
            {
              url: res.data.shopImg,
            },
          ];
        }
      },
      err => console.error('error', err),
    );

    this._shopServer.getFareInfo().subscribe(
      res => {
        console.log('success', res);
        if (res.success) {
          this.form3.patchValue({
            fee: res.data.fee,
            fullFee: res.data.fullFee,
            info: res.data.info,
          });
        }
      },
      err => console.error('error', err),
    );

    this.getData();
  }

  submit() {
    this.submitting = true;
    // setTimeout(() => {
    //   this.submitting = false;
    //   this.msg.success(`提交成功`);
    //   this.cdr.detectChanges();
    // }, 1000);

    this.form.value.shopImg = this.downloadPath;

    this._shopServer.edit(this.form.value).subscribe(
      res => {
        this.submitting = false;
        console.log('success', res);
        if (res.success) {
          this.msg.success(`操作成功`);
        }
      },
      err => {
        this.submitting = false;
        console.error('error', err);
      },
    );

    console.log(this.form.value);
  }

  submit3() {
    this.submitting = true;

    this._shopServer.edit4Fare(this.form3.value).subscribe(
      res => {
        this.submitting = false;
        console.log('success', res);
        if (res.success) {
          this.msg.success(`操作成功`);
        }
      },
      err => {
        this.submitting = false;
        console.error('error', err);
      },
    );
  }

  submit4() {
    this.submitting = true;

    this._shopServer.edit4Fare(this.form3.value).subscribe(
      res => {
        this.submitting = false;
        console.log('success', res);
        if (res.success) {
          this.msg.success(`操作成功`);
        }
      },
      err => {
        this.submitting = false;
        console.error('error', err);
      },
    );
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };
}
